package com.carful.xigua.modules.common.security;

import com.carful.xigua.modules.common.util.SecurityContextUtils;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 组合权限验证器
 *
 * @author Administrator
 * Date 2024/2/7 10:03
 * Description
 */

@Component("CompositePermissionAny")
@Slf4j
public class CompositePermissionAny implements PermissionHandler<Object, Object> {

    @Autowired
    private SecurityContextUtils securityContextUtils;

    @Autowired
    private ApplicationContext applicationContext;

    private List<PermissionHandler> handlers = new ArrayList<>();

    @Autowired
    public CompositePermissionAny(UriPermissionHandler permissionByUri, RolePermissionHandler permissionByRole) {
        handlers.add(permissionByUri);
        handlers.add(permissionByRole);
    }

    @PostConstruct
    public void init() {
        Map<String, PermissionHandler> beans = applicationContext.getBeansOfType(PermissionHandler.class);
        for (Map.Entry<String, PermissionHandler> entry : beans.entrySet()) {
            if (entry.getKey().equals("CompositePermissionAny")) {
                continue;
            }
            handlers.add(entry.getValue());
        }
    }


    @Override
    public boolean isPre(Object target, Object... args) {
        return false;
    }

    @Override
    public boolean isPost(Object returnObject, Object... args) {
        return false;
    }

    @Override
    public boolean preHandle(Object target, Object... args) {
        for (PermissionHandler handler : handlers) {
            if (handler.preHandle(target, args)) {
                String uri = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getRequestURI();
                log.info(handler.getClass() + " 处理权限 " + securityContextUtils.getLoginUserDetails().getUsername() + " -> " + uri);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean postHandle(Object returnObject, Object... args) {
        for (PermissionHandler handler : handlers) {
            if (handler.postHandle(returnObject, args)) return true;
        }
        return false;
    }
}
